/*  Copyright (C) 2009 Jos van der Til
    
    This file is part of the Fluent Metadata Library.

    The Fluent Metadata Library is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    The Fluent Metadata Library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with the Fluent Metadata Library.  If not, see <http://www.gnu.org/licenses/>.
 */
using System;
using System.ComponentModel.DataAnnotations;

namespace FluentMetadata.AttributeBuilders.Validation
{
    public class StringLengthAttributeBuilder : IStringLengthAttributeBuilder
    {
        private string _error;
        private int _maxLength;
        private int _minLength = -1;

        #region IAttributeContainer Members

        public Attribute InnerAttribute
        {
            get
            {
                StringLengthAttribute attribute;

                if (_maxLength < _minLength)
                    throw new ArgumentException("_maxLength < _minLength");
                if (_minLength != -1)
                    attribute = new StringLengthAttribute(_maxLength) {MinimumLength = _minLength};
                else
                    attribute = new StringLengthAttribute(_maxLength);

                if (!string.IsNullOrEmpty(_error))
                    attribute.ErrorMessage = _error;

                return attribute;
            }
        }

        #endregion

        #region IStringLengthAttributeBuilder Members

        public IStringLengthAttributeBuilder Minimum(int length)
        {
            _minLength = length;
            return this;
        }

        public IStringLengthAttributeBuilder Maximum(int length)
        {
            _maxLength = length;
            return this;
        }

        public IStringLengthAttributeBuilder WithErrorMessage(string errorMessage)
        {
            _error = errorMessage;
            return this;
        }

        #endregion
    }
}